#include "../../server/mq_binding.hpp"
#include <iostream>
#include <gtest/gtest.h>

using namespace xzt;

BindingManager::ptr p_bm;

class BindingTest: public testing::Environment
{
    virtual void SetUp() override
    {
        p_bm = std::make_shared<BindingManager>("./data/binding.db");
    }

    virtual void TearDown() override
    {
        // recovery_test
        p_bm->clear();
    }
};


TEST(Binding_test, insert_test)
{
    p_bm->bind("Exchange1", "Queue1", "binding_key1", true);
    p_bm->bind("Exchange2", "Queue2", "binding_key2", true);
    p_bm->bind("Exchange1", "Queue3", "binding_key3", true);
    p_bm->bind("Exchange2", "Queue1", "binding_key4", true);

    ASSERT_EQ(p_bm->size(), 4);
}

TEST(Binding_test, select_test)
{
    std::string ename = "Exchange1";
    std::string qname = "Queue1";
    Binding::ptr p_b = p_bm->getBinding(ename, qname);

    ASSERT_NE(p_b.get(), nullptr);
    ASSERT_EQ(p_b->_exchange_name, ename);
    ASSERT_EQ(p_b->_msgqueue_name, qname);
    ASSERT_EQ(p_b->_binding_key, string("binding_key1"));

    auto bindings = p_bm->getExchangeBindings(ename);
    ASSERT_EQ(bindings.size(), 2);
    ASSERT_EQ(bindings[qname]->_msgqueue_name, string("Queue3"));
    ASSERT_EQ(bindings[qname]->_binding_key, string("binding_key3"));
}

// 测试删除 --批次1
// TEST(Binding_test, delete_exchange_test)
// {
//     // e1 - q1, e1 - q3, e2 - q1, e2 - q2
//     std::string ename = "Exchange1";
//     ASSERT_NE(p_bm->getBinding(ename, "Queue1"), nullptr);
//     ASSERT_NE(p_bm->getBinding(ename, "Queue3"), nullptr);

//     p_bm->unbindExchange(ename);

//     ASSERT_EQ(p_bm->getBinding(ename, "Queue1"), nullptr);
//     ASSERT_EQ(p_bm->getBinding(ename, "Queue3"), nullptr);
// }

// 测试删除 --批次2
TEST(Binding_test, delete_queue_test)
{
    // e1 - q1, e1 - q3, e2 - q1, e2 - q2
    std::string qname1 = "Queue1";
    ASSERT_NE(p_bm->getBinding("Exchange1", qname1), nullptr);
    ASSERT_NE(p_bm->getBinding("Exchange2", qname1), nullptr);

    p_bm->unbindMsgQueue(qname1);
    // 保留：e1 - q3, e2 - q2

    ASSERT_EQ(p_bm->getBinding("Exchange1", qname1), nullptr);
    ASSERT_NE(p_bm->getBinding("Exchange1", "Queue3"), nullptr);
    ASSERT_EQ(p_bm->getBinding("Exchange2", qname1), nullptr);
    ASSERT_NE(p_bm->getBinding("Exchange2", "Queue2"), nullptr);

    std::string qname2 = "Queue2";
    p_bm->unbindMsgQueue(qname2);
    // 保留：e1 - q3
    ASSERT_EQ(p_bm->getBinding("Exchange2", "Queue2"), nullptr);
    ASSERT_NE(p_bm->getBinding("Exchange1", "Queue3"), nullptr);
}

TEST(Binding_test, delete_test)
{
    string ename = "Exchange1";
    string qname = "Queue3";

    ASSERT_NE(p_bm->getBinding(ename, qname), nullptr);
    p_bm->unbind(ename, qname);
    ASSERT_EQ(p_bm->getBinding(ename, qname), nullptr);
}


int main(int argc, char* argv[])
{
    testing::InitGoogleTest(&argc, argv);
    testing::AddGlobalTestEnvironment(new BindingTest);
    RUN_ALL_TESTS();

    return 0;
}


